package office.stock.presentation;

import java.io.BufferedOutputStream;
import java.io.IOException;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import office.stock.services.ImageStorage;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

@WebServlet(urlPatterns = "/dynamic-image/*")
public class DynamicImageProvider extends HttpServlet {
    
    private final static Log log = LogFactory.getLog(DynamicImageProvider.class);
    
    private static final long serialVersionUID = 1L;
    
    private final static int MAX_AGE = 60*60*24;
    
    @EJB
    private ImageStorage imageStorage;
    
    @PostConstruct
    public void init() {
	log.debug("Servlet created ");
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String id = req.getParameter("id");
	log.debug("Looking for image " + id);
	byte [] image = imageStorage.read(id);
	resp.setHeader("Cache-Control", "max-age=" + MAX_AGE);
	new BufferedOutputStream(resp.getOutputStream()).write(image);
	
    }
    
}
